﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using CoreLab.Oracle; //using Devart.Data.Oracle; //using Oracle.DataAccess.Client;
using DevExpress.Web.ASPxHeadline;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxCallback;
using DevExpress.Web.ASPxGridView;

using LMD.Constant;
using LMD.Lib.DataClass;
using LMD.Lib.Interface;
using LMD.Lib.Oracle;

public partial class UFTNew : ICPRelationshipPage
{
    public UFTData m_uftData = new UFTData();
    public int m_iEventId = 0;
    public bool m_bSubmitted = false;
    public bool m_bCheckClose = false;

    #region Properties
    #endregion Properties

    #region Event Handlers
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        Page.Title = "ICP Lintasarta: Relationship, Create New User Forum/Training";

        m_iEventId = Context.ReadInt("eid");

        if (!IsPostBack && !IsCallback)
        {
            Session[KSession.UFT_FILTERTEMA] = null;
        	if( m_iEventId > 0 )
        	{
	            //check udah disubmit untuk ID ini
	            m_bSubmitted = DBQuery.EventTable.CheckIsSubmitted(m_iEventId);
	            m_bCheckClose = DBQuery.EventTable.CheckIsClosed(m_iEventId);
	            
        	}
            InitUFTData();
        }
        InitGuestInvitation();
    }
    protected void cbkUFTNew_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = CreateNewUFT(e.Parameter);
    }
    protected void cbkInvitation_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        SubmitInvitation();
    }
    protected void dgGuest_Invitation_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        if (e.Parameters.StartsWith("FILTER"))
        {
            HandleFilter(e.Parameters);
        }
        else if (e.Parameters.StartsWith("ALL"))
        {
            Session[KSession.UFT_FILTERTEMA] = null;
            InitGuestInvitation();
        }
        else
        {
            MoveToSelectedGrid();
        }
    }
    protected void dgSelected_Invitation_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
        if (e.Parameters.ToUpper() == "REFRESH")
        {
            ReloadSelectedGrid(true);
        }
    }

    #endregion Event Handlers

    #region Custom Methods
    protected override void DoSearch(String sxSearchQuery)
    {
        throw new NotImplementedException();
    }

    private void InitUFTData()
    {
        if (m_iEventId > 0)
        {
            // ambil data UFT dari Database
            DataTable dtEventTable = DBQuery.EventTable.GetEventDataByID(m_iEventId);
            m_uftData.sxCode = dtEventTable.Rows[0]["CODE"].ToString();
            m_uftData.dtmEventDate = Convert.ToDateTime(dtEventTable.Rows[0]["EVENT_DATE"]);
            m_uftData.iEventId = Convert.ToInt32(dtEventTable.Rows[0]["P_EVENT_ID"]);
            if (dtEventTable.Rows[0]["INVITATION_ATTACHMENT_ID"] == DBNull.Value)
            {
                m_uftData.iInvitationAttachmentId = 0;
            }
            else
            {
                m_uftData.iInvitationAttachmentId = Convert.ToInt32(dtEventTable.Rows[0]["INVITATION_ATTACHMENT_ID"]);
            }
            if (dtEventTable.Rows[0]["EVENT_ATTACHMENT_ID"] == DBNull.Value)
            {
                m_uftData.iEventAttachmentId = 0;
            }
            else
            {
                m_uftData.iEventAttachmentId = Convert.ToInt32(dtEventTable.Rows[0]["EVENT_ATTACHMENT_ID"]);
            }
            if (dtEventTable.Rows[0]["PRESENTATION_ID"] == DBNull.Value)
            {
                m_uftData.iPresentationId = 0;
            }
            else
            {
                m_uftData.iPresentationId = Convert.ToInt32(dtEventTable.Rows[0]["PRESENTATION_ID"]);
            }
            if (dtEventTable.Rows[0]["LOCATION"] != DBNull.Value)
            {
                m_uftData.sxLocation = dtEventTable.Rows[0]["LOCATION"].ToString();
            }
            if (dtEventTable.Rows[0]["START_TIME"] != DBNull.Value)
            {
                m_uftData.dtmStartTime = Convert.ToDateTime(dtEventTable.Rows[0]["START_TIME"]);
            }
            if (dtEventTable.Rows[0]["END_TIME"] != DBNull.Value)
            {
                m_uftData.dtmEndTime = Convert.ToDateTime(dtEventTable.Rows[0]["END_TIME"]);
            }
        }
        else
        {
            m_uftData.dtmEventDate = DateTime.Now;
        }
    }

    protected void InitGuestInvitation()
    {
        if (m_bCheckClose)
        {
            String sxCARID = ICPUser.ID;
            DataTable dtSelected = DBQuery.CustomerTable.GetCustomerInvitation(m_iEventId, sxCARID);

            dgList.DataSource = dtSelected;
            dgList.DataBind();
            dgList.Columns["CUSTOMER_ID"].Visible = false;

            foreach (DataColumn dc in ((DataTable)dgList.DataSource).Columns)
            {
                if (dc.DataType == typeof(DateTime))
                {
                    ((GridViewDataDateColumn)dgList.Columns[dc.ColumnName]).PropertiesDateEdit.DisplayFormatString = "dd-MMM-yyyy";
                }
            }

            GridViewDataTextColumn companyCol = new GridViewDataTextColumn();
            companyCol.DataItemTemplate = new CompanyTemplate(); // Create a template
            companyCol.Name = "COMPANY";
            companyCol.Caption = "COMPANY";
            companyCol.FieldName = "COMPANY_NAME";
            companyCol.VisibleIndex = 1;
            //dgList.Columns.Insert(1, companyCol);
            dgList.Columns.Add(companyCol);
            dgList.Columns["COMPANY_NAME"].Visible = false;

        }
        else
        {
            ReloadUnselectedGrid(false);

            GridViewCommandColumn x = new GridViewCommandColumn();
            x.Caption = "#";
            x.ShowSelectCheckbox = true;
            x.VisibleIndex = 0;
            x.Width = 25;
            x.Name = "x";

            GridViewColumnCollection dgc = dgCustomerList.Columns;
            if (dgc.IndexOf(dgCustomerList.Columns["x"]) < 0)
            {
                //dgCustomerList.Columns.Insert(0, x);
                dgCustomerList.Columns.Add(x);
            }
            
            dgCustomerList.Columns["CUSTOMER_ID"].Visible = false;

            ReloadSelectedGrid(false);
            dgSelected.Columns["CUSTOMER_ID"].Visible = false;
            DataTable dt = (DataTable)dgCustomerList.DataSource;
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.DataType == typeof(DateTime))
                {
                    ((GridViewDataDateColumn)dgCustomerList.Columns[dc.ColumnName]).PropertiesDateEdit.DisplayFormatString = "dd-MMM-yyyy";
                }
            }
            GridViewDataTextColumn companyCol = new GridViewDataTextColumn();
            companyCol.DataItemTemplate = new CompanyTemplate(); // Create a template
            companyCol.Name = "COMPANY";
            companyCol.Caption = "COMPANY";
            companyCol.FieldName = "COMPANY_NAME";
            companyCol.VisibleIndex = 1;

            GridViewColumnCollection dgc2 = dgCustomerList.Columns;
            if (dgc2.IndexOf(dgCustomerList.Columns["COMPANY"]) < 0)
            {
                //dgCustomerList.Columns.Insert(1, companyCol);
                dgCustomerList.Columns.Add(companyCol);
            }

            
            dgCustomerList.Columns["COMPANY_NAME"].Visible = false;

        }
        
    }

    private string CreateNewUFT(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);

        String sxReturn = String.Empty;
        String[] sxTime;
        double dHours;
        double dMinutes;
        DateTime dtmTime;

        foreach (String sxRow in sxSplitted)
        {
            String[] sxRowSplitted = sxRow.Split(new String[] { KGlobal.NEWLINE }, StringSplitOptions.None);

            switch (sxRowSplitted[0].ToUpper())
            {
                case KUFT.JENISID:
                    m_uftData.iEventId = Int16.Parse(sxRowSplitted[1]);
                    break;
                case KUFT.EVENT_CODE:
                    m_uftData.sxCode = sxRowSplitted[1];
                    break;
                case KUFT.TANGGALEVENT:
                    m_uftData.dtmEventDate = DateTime.Parse(sxRowSplitted[1]);
                    break;
                case KUFT.INVITATIONATTACHMENTID:
                    m_uftData.iInvitationAttachmentId = Int16.Parse(sxRowSplitted[1]);
                    break;
                case KUFT.LOCATION:
                    m_uftData.sxLocation = sxRowSplitted[1];
                    break;
                case KUFT.STARTTIME:
                    sxTime = sxRowSplitted[1].Split(new String[] {":"}, StringSplitOptions.None);
                    dHours = Convert.ToDouble(sxTime[0]);
                    dMinutes = Convert.ToDouble(sxTime[1]);
                    dtmTime = m_uftData.dtmEventDate;
                    dtmTime = dtmTime.AddHours(-(dtmTime.Hour) + dHours);
                    dtmTime = dtmTime.AddMinutes(-(dtmTime.Minute) + dMinutes);
                    m_uftData.dtmStartTime = dtmTime;// DateTime.Parse(sxRowSplitted[1]);
                    break;
                case KUFT.ENDTIME:
                    sxTime = sxRowSplitted[1].Split(new String[] { ":" }, StringSplitOptions.None);
                    dHours = Convert.ToDouble(sxTime[0]);
                    dMinutes = Convert.ToDouble(sxTime[1]);
                    dtmTime = m_uftData.dtmEventDate;
                    dtmTime = dtmTime.AddHours(-(dtmTime.Hour) + dHours);
                    dtmTime = dtmTime.AddMinutes(-(dtmTime.Minute) + dMinutes);
                    m_uftData.dtmEndTime = dtmTime;// DateTime.Parse(sxRowSplitted[1]);
                    break;
            }
        }

        m_uftData.intID = DBQuery.EventTable.SaveEvent(m_uftData);
        sxReturn = m_uftData.intID.ToString();
        return sxReturn;
    }

    private void HandleFilter(String sxParameter)
    {
        String[] sxSplitted = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);
        int iFilterEventId = Convert.ToInt32(sxSplitted[1]);
        Session[KSession.UFT_FILTERTEMA] = iFilterEventId;
        InitGuestInvitation();
    }

    private void MoveToSelectedGrid()
    {
        DataTable dtSelected = (DataTable)dgSelected.DataSource;
        List<object> lsCustIdSelected = new List<object>();
        foreach (DataRow dr in dtSelected.Rows)
        {
            lsCustIdSelected.Add(dr["CUSTOMER_ID"]);
        }
        List<object> keyValues = dgCustomerList.GetSelectedFieldValues("CUSTOMER_ID");
                
        // BEGIN TRANSACTION
        DBLib dbl = new DBLib();
        dbl.BeginTransaction();
        try
        {
            foreach (object obj in keyValues)
            {
                if(lsCustIdSelected.Contains(obj))
                {
                    //Kalau sudah ada di selected grid ga perlu dipindah
                    continue;
                }
                else
                {
                    // INSERT TIAP ROW KE DB
                    InvitationData invData = new InvitationData();
                    invData.intCustID = Convert.ToInt32(obj);
                    invData.intEventID = m_iEventId;
                    invData.sxStatusLain = null;

                    DBQuery.CustomerTable.SaveInvitation(dbl, invData);
                }
            }          
            
            // COMMIT 
            dbl.EndTransaction(true);
        }
        catch (Exception ex)
        {
            // ROLLBACK
            dbl.EndTransaction(false);
            throw ex;
        }

        dgCustomerList.Selection.UnselectAll();
    }

    private void ReloadUnselectedGrid(bool bRefresh)
    {
        int iFilterEventId = -1;
        if (Session[KSession.UFT_FILTERTEMA] != null)
        {
            iFilterEventId = Convert.ToInt32(Session[KSession.UFT_FILTERTEMA]);
            bRefresh = true;
        }

		bRefresh = (iFilterEventId < 0);
        Cached.CustomerTable tblCustomer = new Cached.CustomerTable();
        DataTable dtUnselected = tblCustomer.GetCustomer(m_iEventId, false, iFilterEventId, bRefresh);

        dgCustomerList.DataSource = dtUnselected;
        dgCustomerList.DataBind();

        if (iFilterEventId < 0)
        {
            //dgCustomerList.Columns["T_RELATION_EVENT_ID"].Visible = false;
            dgCustomerList.Columns["CODE"].Visible = false;
            dgCustomerList.Columns["IS_INVITED"].Visible = false;
            dgCustomerList.Columns["IS_ATTENDED"].Visible = false;
            dgCustomerList.Columns["IS_CONFIRMED"].Visible = false;
            dgCustomerList.Columns["IS_BLACKLISTED"].Visible = false;
            dgCustomerList.Columns["EVENT_DATE"].Visible = false;
            dgCustomerList.Columns["X_COUNT"].Visible = false;
            dgCustomerList.Columns["X_MAX"].Visible = false;
        }
        else
        {
            //dgCustomerList.Columns["T_RELATION_EVENT_ID"].Visible = false;
            dgCustomerList.Columns["EVENT_DATE"].Visible = true;
            dgCustomerList.Columns["CODE"].Visible = true;
            dgCustomerList.Columns["IS_INVITED"].Visible = true;
            dgCustomerList.Columns["IS_ATTENDED"].Visible = true;
            dgCustomerList.Columns["IS_CONFIRMED"].Visible = true;
            dgCustomerList.Columns["IS_BLACKLISTED"].Visible = true;
            dgCustomerList.Columns["X_COUNT"].Visible = false;
            dgCustomerList.Columns["X_MAX"].Visible = false;
        }
    }

    private void ReloadSelectedGrid(bool bRefresh)
    {
        Cached.CustomerTable tblCustomer = new Cached.CustomerTable();

        // SELECT DARI DB, MASUKIN KE dgSelected
        DataTable dtSelected = tblCustomer.GetCustomer(m_iEventId, true, -1, bRefresh);


        dgSelected.DataSource = dtSelected;
        dgSelected.DataBind();

        foreach (DataColumn dc in dtSelected.Columns)
        {
            if (dc.DataType == typeof(DateTime))
            {
                ((GridViewDataDateColumn)dgSelected.Columns[dc.ColumnName]).PropertiesDateEdit.DisplayFormatString = "dd-MMM-yyyy";
            }
        }
        GridViewDataTextColumn companyCol = new GridViewDataTextColumn();
        companyCol.DataItemTemplate = new CompanyTemplate(); // Create a template
        companyCol.Name = "COMPANY";
        companyCol.Caption = "COMPANY";
        companyCol.FieldName = "COMPANY_NAME";
        companyCol.VisibleIndex = 1;
        //dgSelected.Columns.Insert(1, companyCol);
        if (dgSelected.Columns["COMPANY"] == null)
        {
            dgSelected.Columns.Add(companyCol);
        }
        dgSelected.Columns["COMPANY_NAME"].Visible = false;

    }

    private void SubmitInvitation()
    {
        // UPDATE DB, SET FLAG STATUS
        DBLib dbl = new DBLib();
        dbl.BeginTransaction();
        try
        {
            DBQuery.CustomerTable.UpdateStatusInvitation(dbl,m_iEventId);
            GetCPTeknisAsGuest(dbl);
            dbl.EndTransaction(true);
        }
        catch (Exception ex)
        {
            dbl.EndTransaction(false);
            throw ex;
        }
        
    }

    private void GetCPTeknisAsGuest(DBLib dbl)
    {
        //SAVE CPTeknis as Guest by default
        //ambil invID, custID by eventId
        DataTable dtInvitation = DBQuery.CustomerTable.GetInvitationByEventId(m_iEventId);
        //ambil getCPTeknisByCustId
        List<GuestData> lsGuestData = new List<GuestData>();
        GuestData guestData;
        foreach (DataRow dr in dtInvitation.Rows)
        {
            int iCustId = Convert.ToInt32(dr["CUSTOMER_ID"]);
            object[] objCPTeknis = DBQuery.CustomerTable.getCPTeknisByCustId(iCustId);
            //assign guestData(CPID, invID)
            if (objCPTeknis != null)
            {
                foreach (object obj in objCPTeknis)
                {
                    guestData = new GuestData();
                    guestData.iCPId = Convert.ToInt32(obj);
                    guestData.iInvitationId = Convert.ToInt32(dr["T_RELATION_INVITATION_ID"]);
                    guestData.sxCreatedBy = ICPUser.ID;
                    lsGuestData.Add(guestData);
                    guestData = null;
                }
            }
            else
            {
                continue;
            }
        }
        //DBLib dbl = new DBLib();
        //dbl.BeginTransaction();
        //try
        //{
            foreach (GuestData guest in lsGuestData)
            {
                //saveGuest(guestData)
                DBQuery.CustomerTable.SaveGuest(dbl, guest);
            }
            //COMMIT
        //    dbl.EndTransaction(true);
        //}
        //catch (Exception ex)
        //{
            //ROLLBACK
        //    dbl.EndTransaction(false);
        //    throw ex;
        //}
    }
    #endregion Custom Methods

    class CompanyTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            GridViewDataItemTemplateContainer gridContainer =
                (GridViewDataItemTemplateContainer)container;

            String sxCustID = gridContainer.Grid.GetRowValues(gridContainer.VisibleIndex,
                                "CUSTOMER_ID").ToString();
            String sxCompName = gridContainer.Grid.GetRowValues(gridContainer.VisibleIndex,
                                "COMPANY_NAME").ToString();
            String sxOutput = GridColumnManager.GetCompanyLinkColumn(
                                sxCustID, sxCompName);
            LiteralControl ltr = new LiteralControl(sxOutput);
            container.Controls.Add(ltr);
        }
    }
}
